<template>
  <a-modal
    v-model:visible="modalVisible"
    :title="`${editRow ? $t('common.edit') : $t('common.add')}${$t('osManager.task')}`"
    @cancel="fnClose"
    :maskClosable="false"
    @ok="fnAddTask"
    width="900px"
  >
    <a-form :model="form" ref="formRef" :rules="rules" :label-col="{ span: 5 }" :wrapper-col="{ span: 16 }">
      <a-form-item :label="$t('osManager.taskName')" prop="taskName" required>
        <a-input v-model:value="form.taskName"></a-input>
      </a-form-item>
      <a-form-item :label="$t('osManager.hostSelect')" prop="hosts">
        <host-choose
          ref="host"
          @change="fnChangeHost"
          :refresh="hostRefresh"
          @hadRefresh="hostRefresh = false"
        ></host-choose>
      </a-form-item>
      <a-form-item :label="$t('osManager.selectPackage')" prop="assets">
        <a-select
          v-model:value="form.assets"
          :placeholder="$t('osManager.selectPackagePlaceholder')"
          mode="multiple"
        >
          <a-select-option v-for="ass in assets" :key="ass.asset_id" :value="ass.asset_id">
            {{ ass.asset_name[lang === 'en' ? 'en' : 'zh'] }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { api } from '@/api'
import { fnIsError } from './components'
import hostChoose from './hostChoose.vue'
import { storeToRefs } from 'pinia'
import { useLangStore } from '@/store'

export default {
  emits: ['close'],
  name: 'addInspection',
  props: ['isShow', 'editRow', 'type'],
  components: {
    hostChoose,
  },
  computed: {
    modalVisible() {
      return this.isShow;
    }
  },
  data() {
    const { lang } = useLangStore()
    const checkName = (rule, value, callback) => {
      if (!value.trim()) {
        callback(new Error(this.$t('osManager.enterTaskName')))
        return
      }
      if (value.trim().length > 128) {
        callback(new Error(this.$t('osManager.taskNameLength')))
        return
      }
      callback()
    }
    const checkHost = (rule, value, callback) => {
      // value为Object类型
      if (!Object.keys(value).length) {
        callback(new Error(this.$t('osManager.selectAtLeastAHost')))
        return
      }
      callback()
    }
    return {
      lang,
      hostRefresh: false,
      assets: [],

      form: {
        taskName: '',
        hosts: {},
        assets: [],
      },
      rules: {
        taskName: [
          { validator: checkName, trigger: 'blur' },
          {
            pattern: /^[0-9a-zA-Z_\-\u4e00-\u9fa5][0-9a-zA-Z_.\-\u4e00-\u9fa5]*$/,
            message: this.$t('osManager.taskNameValid'),
          },
        ],
        hosts: [{ required: true, message: this.$t('osManager.selectAtLeastAHost') }, { validator: checkHost }],
        assets: [
          {
            required: true,
            message: this.$t('osManager.selectPackagePlaceholder'),
            trigger: 'change',
          },
        ],
      },
    }
  },
  watch: {
    isShow(val) {
      if (val) {
        this.initPage()
      }
    },
  },
  async mounted() {
    await this.fnRefreshAsset()
  },
  methods: {
    async fnRefreshAsset() {
      const [_, res] = await api.fnGetInspectionAsset(this.type)
      this.assets = res.asset_infos.map(item => {
        item.label = `${item.asset_name.zh}_${item.version}`
        return item
      })
    },
    async initPage() {
      this.form = {
        taskName: '',
        hosts: {},
        assets: [],
      }
      this.$nextTick(() => {
        this.hostRefresh = true
        if (this.$refs.formRef) {
          this.$refs.formRef.clearValidate()
        }
      })
    },
    fnChangeHost(selectHostId) {
      this.form.hosts = selectHostId
      this.$refs.formRef.validateFields('hosts')
    },
    fnClose() {
      this.$emit('close')
    },
    async fnAddTask() {
      await this.$refs.formRef.validate();
      const param = {
        task_name: this.form.taskName,
        assets: this.form.assets,
        host_ids: this.form.hosts,
        task_type: this.type,
      }
      const [_, res] = await api.fnAddTask(param)
      this.$emit('close', true)
    },
  },
}
</script>

<style scoped>
:deep(.el-select-dropdown) {
  width: 300px;
}
</style>
